import React, { useState, useEffect, useCallback, useRef } from "react";
import { Button, Table, Space, Form, Input, Popconfirm, Select } from "antd";
import { DeleteOutlined, SearchOutlined, SyncOutlined, DownOutlined, ReloadOutlined } from "@ant-design/icons";
import TableLayout, {
  SearchContainer,
  SearchAction,
  SearchForm,
  MainContainer,
} from "@/components/templates/TableLayout";
import { ButtonCollapsed } from "@/components/iteration";
import { AuthButton } from "@/components/auth";
import { getOnlineUserList, OnlineUserExit } from "@/api/monitor/online";
import PropTypes from "prop-types";

const AUTH_PERMISSION = {
  EXIT: "monitor:online:exit",
};

const HeaderComponent = ({ onSearch = () => {}, onRefresh = () => {} }) => {
  const [folded, setFolded] = useState(false);
  const [searchType, setSearchType] = useState("keyword");
  const inputRef = useRef(null);

  const onFinish = (values) => {
    const data = Object.entries(values).filter(([_, value]) => !!value);
    data.length && onSearch(Object.fromEntries(data));
  };

  const hanldeSearch = () => {
    const value = inputRef.current.input.value;
    value && onSearch({ [searchType]: value });
  };

  const options = [
    { label: "综合搜索", value: "keyword", placeholder: "综合搜索" },
    { label: "登录地址", value: "ipAddress", placeholder: "请输入登录地址" },
    { label: "用户名称", value: "userName", placeholder: "请输入用户名称" },
  ];

  return (
    <SearchContainer>
      <SearchAction>
        <Space.Compact>
          <Select
            defaultValue={searchType}
            style={{ width: 120 }}
            options={options}
            onChange={(v) => setSearchType(v)}
          />
          <Input ref={inputRef} placeholder={options.find((item) => item.value === searchType).placeholder} />
          <Button icon={<SearchOutlined />} onClick={hanldeSearch} />
        </Space.Compact>

        <Space>
          <Button icon={<ReloadOutlined />} onClick={onRefresh} />
          <ButtonCollapsed
            type="link"
            icon={<DownOutlined />}
            iconPosition="end"
            collapsed={folded}
            onClick={() => setFolded(!folded)}
          >
            高级搜索
          </ButtonCollapsed>
        </Space>
      </SearchAction>

      <SearchForm collapse={folded}>
        <Form layout="inline" autoComplete="off" onFinish={onFinish} onReset={() => onSearch()}>
          <Form.Item name="ipAddress" label="登录地址">
            <Input placeholder="请输入登录地址" />
          </Form.Item>
          <Form.Item name="userName" label="用户名称">
            <Input placeholder="请输入用户名称" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                搜索
              </Button>
              <Button icon={<SyncOutlined />} htmlType="reset">
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </SearchForm>
    </SearchContainer>
  );
};
HeaderComponent.propTypes = {
  onSearch: PropTypes.func,
  onRefresh: PropTypes.func,
};

const GeneralComponent = () => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);

  const onGetData = useCallback((options = {}) => {
    setLoading(true);
    getOnlineUserList(options)
      .then((res) => setDataSource(res))
      .finally(() => setLoading(false));
  }, []);
  // 初始化数据
  useEffect(() => onGetData(), [onGetData]);

  const onSearch = (values) => {
    onGetData(values);
  };

  const onExit = async (value) => {
    await OnlineUserExit(value);
    onGetData();
  };

  const columns = [
    { key: "index", title: "序号", render: (_, __, index) => index + 1 },
    { key: "tokenId", title: "会话", dataIndex: "tokenId" },
    { key: "userName", title: "用户名称", dataIndex: "userName" },
    { key: "ipAddress", title: "IP地址", dataIndex: "ipAddress" },
    { key: "loginLocation", title: "登录地点", dataIndex: "loginLocation" },
    { key: "browser", title: "浏览器", dataIndex: "browser" },
    { key: "os", title: "操作系统", dataIndex: "os" },
    { key: "loginTime", title: "登录时间", dataIndex: "loginTime" },
    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space>
          <Popconfirm
            title="系统提示"
            description={`是否确认强退该用户？`}
            onConfirm={() => onExit(record.key)}
            okText="是"
            cancelText="否"
          >
            <AuthButton auth={AUTH_PERMISSION.EXIT} type="link" danger icon={<DeleteOutlined />}>
              强退
            </AuthButton>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <TableLayout>
      <HeaderComponent onSearch={onSearch} onRefresh={() => onGetData()} />
      <MainContainer>
        <Table size="middle" loading={loading} columns={columns} dataSource={dataSource} pagination={false} />
      </MainContainer>
    </TableLayout>
  );
};

export default GeneralComponent;
